import mongoose = require('mongoose');
import q = require('bluebird');

mongoose.Promise = q;


//-----------------

//================
import WebPageBase from "./WebPageBase";
import fs = require('fs');

class FileListProvider extends WebPageBase{
    public queryFileList(path: string){ 
        const defaultPath = path;
        const me = this;
        let promise = new q((resolve,reject)=>{
            fs.readdir(defaultPath, (err: NodeJS.ErrnoException, files: string[]) =>{
                let dataResult = me.getFilelistUnderPath(defaultPath, "", files, 0, 0, []);
    
                resolve(dataResult.data);
            });
        });

        return promise;
    }

    protected getFilelistUnderPath(defaultPath:string, extraPath:string, files:string[], pageSize:number, skip:number, blackList: string[]):any{
        if(!files || files.length <= 0){
            return {"data":[], "count":0};  
        }
        let dir = defaultPath + extraPath;
        let retList = [];
        let totalCount = 0;
        for(let i = 0; i < files.length; i++){
            if(files[i].startsWith(".")){
                continue;
            }
            if(blackList.length > 0 && blackList.indexOf(files[i]) >= 0){
                continue;
            }
            if(totalCount <= skip - 1){
                totalCount++;
                continue;
            }
            if(pageSize > 0 && retList.length >= pageSize){
                totalCount++;
                continue;
            }
            totalCount++;
            try{
                let stats = fs.lstatSync(dir+""+files[i]);
                let isFolder = stats.isDirectory();
                let isImage = isFolder ? false : this.checkImage(files[i]);
                let typeStr = isFolder ? "folder" : isImage ? "image" : "other";
                let shortPath = this.shortPath(defaultPath, dir+""+files[i]);
                retList.push({"filename":files[i], "type":typeStr, "path":shortPath});     
            }
            catch(ex){
                console.log(ex.message);
            }
        }
        return {"data":retList, "count":totalCount};
    }
    protected shortPath(defaultPath:string, path:string):string{
        return path.replace(defaultPath, "");
    }
    private checkImage(filename:string):boolean{
        if(filename.endsWith(".png") || 
        filename.endsWith(".jpg") ||
        filename.endsWith(".gif") ){
            return true;
        }
        return false;
    }
    
}

export default FileListProvider;